package com.elangzhi.ssm.modules.shop.app;

import com.elangzhi.ssm.controller.json.Tip;
import com.elangzhi.ssm.model.Account;
import com.elangzhi.ssm.model.Shop;
import com.elangzhi.ssm.modules.goods.services.GoodsService;
import com.elangzhi.ssm.modules.image.services.ImageService;
import com.elangzhi.ssm.modules.shop.services.ShopService;
import com.elangzhi.ssm.modules.shopEvent.services.ShopEventService;
import com.elangzhi.ssm.services.AccountService;
import com.elangzhi.ssm.tools.UUIDFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.Date;

/**
* 店铺 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/shop")
public class AppShopController {

    /**
     * 申请注册店铺
     * @param shop
     * @return
     */
    @RequestMapping("register")
    @ResponseBody
    public Tip register(Shop shop){
        Account account = accountService.findByUserName(shop.getUserName());
        if(account != null){
            return new Tip(2);
        }

        shop.setId(UUIDFactory.getLongId());
        shop.setStatus(0);
        shop.setSetTime(new Date());
        shop.setIcon("/images/account/default_head.jpg");
        shop.setVip("1");

        try {
            shopService.insert(shop);
            registerAccount(shop);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册商铺出错");
            return new Tip(1);
        }
    }

    /**
     * 注册店铺账号
     * @param shop
     */
    private void registerAccount(Shop shop) throws Exception {
        Account account = new Account();
        account.setId(UUIDFactory.getLongId());
        account.setStatus(1);
        account.setType(2);
        account.setInfoId(shop.getUserId());
        account.setUserName(shop.getUserName());
        account.setPassword(shop.getPassword());
        accountService.insert(account);
    }

    /**
     * 根据店铺id获取店铺信息
     * @param id id
     * @return 实体 带图片和商品列表
     */
    @RequestMapping("findById")
    @ResponseBody
    public Shop findById(@RequestParam Long id){

        try {
            return shopService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Shop();
        }
    }



    //---------------------------- property -------------------------------

    @Resource
    private ShopService shopService;

    @Resource
    private AccountService accountService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ImageService imageService;

    @Resource
    private ShopEventService shopEventService;
}
